package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author Dugen.Zhu
 * @date 2020-01-05 20:11
 */
@Controller
@RequestMapping("/memberMobile")
public class MemberMobileController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @RequestMapping("/login")
    @ResponseBody
    public Result login(HttpServletResponse response, @RequestBody Map loginInfo) {
        //1.判断验证码是否正确
        String telephone_user = (String) loginInfo.get("telephone");
        String code_user = (String) loginInfo.get("validateCode");
        String code = jedisPool.getResource().get(telephone_user + RedisMessageConstant.SENDTYPE_LOGIN);
        if (code == null) {
            return new Result(false, MessageConstant.VALIDATECODE_EXPIRED);
        }
        if (!(code_user != null && code_user.length() > 0)) {
            return new Result(false, MessageConstant.VALIDATECODE_NOTNULL);
        }
        //验证码不正确
        if (!code_user.equals(code)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        Member member = memberService.login(telephone_user);
        if (member == null) {
            //未注册会员，那么直接注册
            Member member1 = new Member();
            member1.setPhoneNumber(telephone_user);
            member1.setRegTime(new Date());
            memberService.add(member1);
        }
        //向客户端写入cookie数据
        Cookie cookie = new Cookie("login_member_telephone",telephone_user);
        //设置cookie有效期为30天
        cookie.setMaxAge(60*60*24*30);
        //如果要共享，则可以将path设置为"/",该共享只能在该服务器内
        cookie.setPath("/");
        response.addCookie(cookie);

        //将会员信息写入Redis
        String json = JSON.toJSON(member).toString();
        jedisPool.getResource().setex(telephone_user,60*30,json);

        return new Result(true, MessageConstant.LOGIN_SUCCESS);
    }
}
